﻿const cloud = require("wx-server-sdk");
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();
const _ = db.command;

const normalizeString = value => (typeof value === "string" ? value.trim() : "");

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const operatorOpenID = wxContext.OPENID;
  const activityID = normalizeString(event.activityID || event.ActivityID);
  const groupID = normalizeString(event.groupID || event.GroupID);
  const deletedOpenID = normalizeString(event.deletedOpenID || event.targetOpenID);

  if (!operatorOpenID) {
    return { success: false, error: "未获取到操作用户" };
  }
  if (!activityID) {
    return { success: false, error: "缺少活动编号" };
  }
  if (!deletedOpenID) {
    return { success: false, error: "缺少报名人编号" };
  }

  try {
    const activityDoc = await db
      .collection("Activity_Information")
      .doc(activityID)
      .get()
      .catch(() => null);

    if (!activityDoc || !activityDoc.data) {
      return { success: false, error: "未找到活动信息" };
    }

    if (activityDoc.data.PublisherOpenID !== operatorOpenID) {
      return { success: false, error: "无权删除该报名" };
    }

    const transaction = await db.startTransaction();

    try {
      let groupFilter = {};
      if (groupID) {
        groupFilter = { GroupID: groupID };
      } else {
        const groupDocs = await transaction
          .collection("Activity_Group_Information")
          .where({ ActivityID: activityID })
          .field({ _id: true })
          .get();

        const groupIDs = Array.isArray(groupDocs.data)
          ? groupDocs.data.map(item => item._id)
          : [];

        if (groupIDs.length === 0) {
          await transaction.rollback();
          return { success: false, error: "未找到报名分组" };
        }
        groupFilter = { GroupID: _.in(groupIDs) };
      }

      await transaction
        .collection("Group_Registration_Information")
        .where(Object.assign({ OpenID: deletedOpenID }, groupFilter))
        .remove();

      const fieldDocs = await transaction
        .collection("Activity_Registration_Information_Fields")
        .where({ ActivityID: activityID })
        .field({ FieldID: true, _id: true })
        .get();

      const fieldIDs = Array.isArray(fieldDocs.data)
        ? fieldDocs.data.map(item => item.FieldID || item._id)
        : [];

      if (fieldIDs.length > 0) {
        await transaction
          .collection("Group_Registration_Custom_Fields")
          .where({
            FieldID: _.in(fieldIDs),
            OpenID: deletedOpenID
          })
          .remove();
      }

      await transaction.commit();
      return { success: true };
    } catch (error) {
      await transaction.rollback();
      console.error("deleteRegistrant transaction error", error);
      return { success: false, error: "删除失败，请稍后重试" };
    }
  } catch (error) {
    console.error("deleteRegistrant error", error);
    return { success: false, error: "删除失败，请稍后重试" };
  }
};
